<template>
  <div class="login-container">
    <!-- 欢迎标题 -->
    <h2 class = "welcome-title">Welcome back!<br>Glad to see you, Again!</h2>

    <form @submit.prevent="handleLogin">
      <div>
        <label>用户名：</label>
        <input v-model="username" type="text" placeholder="Enter your Numbers" required />
      </div>
      <div>
        <label>密码：</label>
        <input type="password" v-model="password" placeholder="Enter your password" required />
      </div>
      <button type="submit" class="login-button">Login</button>
      <p v-if="error" class="error">{{ error }}</p>
    </form>

    <p style="margin-top: 10px;">
      还没有账号？
      <router-link to="/register">立即注册</router-link>
    </p>
    <p style="margin-top: 10px;">
      忘记密码了吗？
      <router-link to="/reset-password">点此重置密码</router-link>
    </p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user.js'
import { login, setAuthToken } from '@/utils/auth.js'

const router = useRouter()
const userStore = useUserStore()

const username = ref('')
const password = ref('')
const error = ref('')

const handleLogin = async () => {
  try {
    const res = await login(username.value, password.value)
    if (res.data.code === 0) {
      const { token, username: uname, userId, permissions } = res.data.data

      setAuthToken(token)
      userStore.loginSuccess({
        username: uname,
        userId,
        permissions,
        token  // ✅ 加上 token
      })

      // ✅ 强制刷新一次 token 保证后续守卫逻辑中读取正确
     await  userStore.refreshToken()

      error.value = ''

      // ✅ 登录后根据权限跳转
      if (permissions.includes('ADMIN')) {
        router.push('/admin')
      } else {
        router.push('/')
      }
    } else {
      error.value = res.data.message || '登录失败'
    }
  } catch (err) {
    error.value = err.response?.data?.message || '登录失败'
  }
}
</script>

<style scoped>
.login-container {
  max-width: 360px;
  margin: 60px auto;
  font-family: 'Inter', sans-serif;
  padding: 20px;
}

.welcome-title {
  text-align: center;
  font-size: 26px;
  font-weight: 700;
  color: #111827;
  margin-bottom: 40px;
  line-height: 1.5;
}

form label {
  display: block;
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 6px;
}

input {
  width: 100%;
  padding: 12px 14px;
  font-size: 14px;
  border: 1px solid #d1d5db;
  border-radius: 10px;
  margin-bottom: 20px;
  outline: none;
  box-sizing: border-box;
}

input::placeholder {
  color: #9ca3af;
}

.login-button {
  width: 100%;
  background-color: #111827;
  color: white;
  padding: 14px;
  font-size: 16px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-button:hover {
  background-color: #1f2937;
}

.error {
  color: #ef4444;
  margin-top: 10px;
  text-align: center;
}

a {
  color: #10b981; /* Tailwind green-500 */
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}
</style>

